
class BaiduEditorController < ApplicationController
  skip_before_filter :verify_authenticity_token

  #{"originalName":"demo.jpg","name":"demo.jpg","url":"upload\/demo.jpg","size":"99697","type":".jpg","state":"SUCCESS"}
  def upload_image
    if params[:upfile].present?
      discussion_attachment = ProductAttachment.new
      discussion_attachment.file = params[:upfile]
      if discussion_attachment.valid?
        discussion_attachment.user = current_user
        if discussion_attachment.save
          render :text => upload_success_json(discussion_attachment)
        else
          render_upload_fail
        end
      else
        render_upload_fail
      end
    else
      render_upload_fail
    end
  end

  private

  def upload_success_json discussion_attachment
    {
      url: discussion_attachment.file.default_resize_url,
      name: discussion_attachment.filename,
      originalName: discussion_attachment.original_filename,
      size: discussion_attachment.file_size,
      type: discussion_attachment.content_type,
      state: 'SUCCESS'
    }.to_json.to_s
  end

  def render_upload_fail
    render :text => {:state => 'FAILURE'}.to_json.to_s
  end

end

